import { FunctionComponent, useCallback } from 'react';
import { Typography } from 'antd';
import { ComponentConfType, componentConfGroup } from '../../../../components/quesitonComponents/index';
import styles from './componentsLib.module.scss';
import useQuestionStore, { ComponentInfoType } from '../../../../zustandStore/questionStore';
import { v4 as uuidv4 } from 'uuid';

const { Title } = Typography;
const ComponentsLib: FunctionComponent = () => {
  const changeSelectedId = useQuestionStore((state) => state.changeSelectedId);
  const addComponents = useQuestionStore((state) => state.addComponents);
  //获取左侧组件
  const getComponent = useCallback((c: ComponentConfType) => {
    const { Component, type, defaultProps } = c;
    //将组件库组件添加到画布
    const addComponentToCanvas = () => {
      const newComponent: ComponentInfoType = {
        id: uuidv4(),
        type,
        title: c.title,
        props: defaultProps,
      };
      addComponents(newComponent);
      changeSelectedId(newComponent.id);
    };
    return (
      <div className={styles.wrapper} key={c.type} onClick={() => addComponentToCanvas()}>
        <div className={styles.component}>
          <Component {...c.defaultProps} />
        </div>
      </div>
    );
  }, []);
  return (
    <>
      {componentConfGroup.map((group, index) => {
        return (
          <div key={index}>
            <Title
              level={3}
              style={{
                color: 'skyblue',
                fontSize: '16px',
                marginTop: index > 0 ? '20px' : '0',
              }}>
              {group.groupName}
            </Title>
            <div>{group.components.map((c) => getComponent(c))}</div>
          </div>
        );
      })}
    </>
  );
};

export default ComponentsLib;
